既然已經有了 waiting group
為什麼還需要 error group 呢?
Using errgroup
As you may have surmised from the code comments, we have a problem—no error propagation. Any of these individual network calls might fail, time out, or otherwise produce an error. In the real world, returning partial results is often better than failing completely, but for our example, let’s assume that if any part of the process fails, we’d like to immediately exit the entire operation and return the error for whatever piece failed.
https://www.fullstory.com/blog/why-errgroup-withcontext-in-golang-server-handlers/
昨天我的 goroutine 中並沒有任何的錯物回傳,在 goroutine 的每一次執行當中都是有『機會』發生錯誤的,如果要撈出錯誤就必須另外存一個 chan 並塞入 error
在現實世界當中,『部分成功』通常比『完全失敗』來得好(當然這要看情境,有時候部分成功但程式繼續往下執行的話造成的麻煩可能後續要補的動作變得更加繁複,這個先不討論)
errgroup 的概念是如果有任何一個 goroutine 失敗的話就要『停止全部任務』並『全部取消』
Package errgroup provides synchronization, error propagation, and Context cancelation for groups of goroutines working on subtasks of a common task.
https://pkg.go.dev/golang.org/x/sync/errgroup
使用到 WithContext 方法
func WithContext(ctx context.Context) (*Group, context.Context)
WithContext returns a new Group and an associated Context derived from ctx.
https://pkg.go.dev/golang.org/x/sync/errgroup#WithContext
WithContext 返回一個新的 Group 並與往前 往後的 ctx 產生關聯性
相關範例:https://pkg.go.dev/golang.org/x/sync/errgroup#example-Group-JustErrors